package servlet;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.Validation;
import model.DataBase;
import model.Field;
import model.Table;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utils.JdbcUtil;
import utils.RequestUtil;
import utils.ResponseUtil;
import dao.DataBaseDao;
import dao.FieldDao;
import dao.TableDao;

@WebServlet(description = "DataBaseServlet", urlPatterns = { "/DataBaseServlet" })
public class DataBaseServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JdbcUtil dbUtil = new JdbcUtil();
	DataBaseDao dbDao = new DataBaseDao();
	TableDao tDao = new TableDao();
	FieldDao fDao = new FieldDao();

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String method = RequestUtil.get(request.getParameter("method"));
		if (method.equals("getDBs")) {
			getDBs(request, response);
		} else if (method.equals("addDBs")) {
			try {
				addDBs(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (method.equals("getTables")) {
			getTables(request, response);
		} else if (method.equals("addField")) {
			try {
				addField(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (method.equals("addTable")) {
			try {
				addTable(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (method.equals("getDBList")) {
			getDBList(request, response);
		} else if (method.equals("deleteDB")) {
			try {
				deleteDB(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (method.equals("getTableList")) {
			getTableList(request, response);
		} else if (method.equals("deleteTable")) {
			try {
				deleteTable(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (method.equals("getFieldList")) {
			getFieldList(request, response);
		} else if (method.equals("deleteField")) {
			try {
				deleteField(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (method.equals("manageDB")) {
			manageDB(request, response);
		} else if (method.equals("manageTable")) {
			manageTable(request, response);
		} else if (method.equals("search")) {
			search(request, response);
		}
	}

	private void getDBs(HttpServletRequest request, HttpServletResponse response) {
		List<DataBase> dbList = dbDao.getDBList();
		String json = JSONArray.fromObject(dbList).toString();
		response.setContentType("text/html;charset=utf-8");// 解决中文乱码问题
		try {
			response.getWriter().write(json);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void addDBs(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String dbName = RequestUtil.get(request.getParameter("dbName"));
		String userName = RequestUtil.get(request.getParameter("userName"));
		String password = RequestUtil.get(request.getParameter("password"));
		String url = RequestUtil.get(request.getParameter("url"));
		String driverName = RequestUtil.get(request.getParameter("driverName"));
		DataBase db = new DataBase();
		JSONObject result = new JSONObject();
		if (!dbName.equals("")) {
			db.setDbName(dbName);
		}
		if (!userName.equals("")) {
			db.setUserName(userName);
		}
		if (!password.equals("")) {
			db.setPassword(password);
		}
		if (!url.equals("")) {
			db.setUrl(url);
		}

		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		Validator validator = factory.getValidator();
		Set<ConstraintViolation<DataBase>> violations = validator.validate(db);
		if (violations.size() == 0) {
			if(dbDao.checkDB(db, driverName) == false){
			dbDao.addDB(db, driverName);
			result.put("Succeed", "0");
			ResponseUtil.write(result, response);}
			else{
				result.put("conFail", "0");
				ResponseUtil.write(result, response);
			}
		} else {
			for (ConstraintViolation<DataBase> violation : violations) {
				result.put("Fail", violation.getMessage());
			}
			ResponseUtil.write(result, response);
		}
	}

	private void getTables(HttpServletRequest request,
			HttpServletResponse response) {
		String dbId = request.getParameter("dbId") == null ? "" : request
				.getParameter("dbId");
		List<Table> tableList = tDao.getTableList(dbId);
		String json = JSONArray.fromObject(tableList).toString();
		try {
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void addField(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String fieldName = RequestUtil.get(request.getParameter("fieldName"));
		String tId = RequestUtil.get(request.getParameter("tableid_field"));
		String fieldType =RequestUtil.get(request.getParameter("fieldType"));
//		String createTime = RequestUtil.get(request.getParameter("createTime"));
//		String location = RequestUtil.get(request.getParameter("location"));

		Field field = new Field();
		JSONObject result = new JSONObject();
		if (!fieldName.trim().equals("")) {
			field.setFieldName(fieldName);
		}
		if (!tId.equals("0")) {
			field.settId(Integer.parseInt(tId));
		}
		if(!fieldType.equals("0")){
			field.setType(fieldType);
		}
		/*
		if(!createTime.trim().equals("")){
			field.setCreateTime(createTime);
		}
		if(!location.trim().equals("")){
			field.setLocation(location);
		}
		*/
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		Validator validator = factory.getValidator();
		Set<ConstraintViolation<Field>> violations = validator.validate(field);
		if (violations.size() == 0) {
			fDao.addField(field);
			result.put("Succeed", "0");
			ResponseUtil.write(result, response);
		} else {
			for (ConstraintViolation<Field> violation : violations) {
				result.put("Fail", violation.getMessage());
				ResponseUtil.write(result, response);
			}
		}

	}

	private void addTable(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String tableName = RequestUtil.get(request.getParameter("tableName"));
		String dbId = RequestUtil.get(request.getParameter("dbName_table"));
		Table tab = new Table();
		JSONObject result = new JSONObject();
		tab.setTableName(tableName);
		if (!dbId.equals("")) {
			tab.setDbId(Integer.parseInt(dbId));
		}
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		Validator validator = factory.getValidator();
		Set<ConstraintViolation<Table>> violations = validator.validate(tab);
		if (violations.size() == 0) {
			tDao.addTable(tab);
			result.put("Succeed", "0");
			ResponseUtil.write(result, response);
		}

		else {
			for (ConstraintViolation<Table> violation : violations) {
				result.put("Fail", violation.getMessage());
				break;
			}
			ResponseUtil.write(result, response);
		}

	}

	private void getDBList(HttpServletRequest request,
			HttpServletResponse response) {
		List<DataBase> dbList = dbDao.getDBList();// 从数据库获取数据
		try {
			displayDBList(request, response, dbList);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}

	}

	private void deleteDB(HttpServletRequest request,
			HttpServletResponse response) {
		String id = RequestUtil.get(request.getParameter("Id"));

		int result = dbDao.deleteDB(id);
		List<DataBase> dbList = dbDao.getDBList();// 从数据库获取数据
		if (request.getParameter("searchName") != null) {
			String name = request.getParameter("searchName");

			dbList = dbDao.getDBListbyName(name);// 从数据库获取数据
			request.setAttribute("searchResult", "metaDBManage.jsp");
			request.setAttribute("searchName", name);
		}
		try {
			if (result <= 0) {
				request.setAttribute("dbList", dbList);
				resultFail(request, response);
			} else {
				request.setAttribute("succeed", "metaDBManage.jsp");
				displayDBList(request, response, dbList);
			}
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}

	}

	private void displayDBList(HttpServletRequest request,
			HttpServletResponse response, List<DataBase> dbList)
			throws ServletException, IOException {
		request.setAttribute("dbList", dbList);
		request.getRequestDispatcher("metaDBManage.jsp").forward(request,
				response);
	}

	private void getTableList(HttpServletRequest request,
			HttpServletResponse response) {
		List<Table> tableList = tDao.getAllTableList();// 从数据库获取数据
		try {
			displayTableList(request, response, tableList);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}

	private void deleteTable(HttpServletRequest request,
			HttpServletResponse response) {
		String id = RequestUtil.get(request.getParameter("Id"));
		String dbId = RequestUtil.get(request.getParameter("dbId"));

		int result = tDao.deleteTable(id);
		List<Table> tableList = tDao.getAllTableList();
		if (request.getParameter("dbId") != null) {
			String dbname = dbDao.getDBname(dbId);
			tableList = tDao.getTableList(dbId);
			request.setAttribute("showDBname", dbname);
			request.setAttribute("dbId", dbId);
		}
		if (request.getParameter("searchName") != null) {
			String name = request.getParameter("searchName");
			tableList = tDao.getTableListbyname(name);
			request.setAttribute("searchResult", "metaDBManage.jsp");
			request.setAttribute("searchName", name);
		}

		try {
			if (result <= 0) {
				request.setAttribute("tableList", tableList);
				resultFail(request, response);
			} else {
				request.setAttribute("succeed", "metaDBManage.jsp");
				displayTableList(request, response, tableList);
			}
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}

	}

	private void displayTableList(HttpServletRequest request,
			HttpServletResponse response, List<Table> tableList)
			throws ServletException, IOException {
		request.setAttribute("tableList", tableList);
		request.getRequestDispatcher("metaDBManage.jsp").forward(request,
				response);
	}

	private void getFieldList(HttpServletRequest request,
			HttpServletResponse response) {
		List<Field> fieldList = fDao.getAllFieldList();// 从数据库获取数据
		try {
			displayFieldList(request, response, fieldList);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}

	private void deleteField(HttpServletRequest request,
			HttpServletResponse response) {
		String id = RequestUtil.get(request.getParameter("Id"));
		String tId = RequestUtil.get(request.getParameter("tableId"));

		int result = fDao.deleteField(id);
		List<Field> fieldList = fDao.getAllFieldList();

		if (request.getParameter("tableId") != null) {
			String tableName = tDao.getTablename(tId);
			fieldList = fDao.getFieldListByTid(tId);// 从数据库获取数据
			request.setAttribute("showTablename", tableName);
			request.setAttribute("tableId", tId);
		}
		if (request.getParameter("searchName") != null) {
			String name = request.getParameter("searchName");

			fieldList = fDao.getFieldListbyTableId(name);
			request.setAttribute("searchResult", "metaDBManage.jsp");
			request.setAttribute("searchName", name);
		}
		try {
			if (result <= 0) {
				request.setAttribute("fieldList", fieldList);
				resultFail(request, response);
			} else {
				request.setAttribute("succeed", "metaDBManage.jsp");
				displayFieldList(request, response, fieldList);
			}
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}

	}

	private void displayFieldList(HttpServletRequest request,
			HttpServletResponse response, List<Field> fieldList)
			throws ServletException, IOException {
		request.setAttribute("fieldList", fieldList);
		request.getRequestDispatcher("metaDBManage.jsp").forward(request,
				response);
	}

	private void resultFail(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("fail", "metaDBManage.jsp");
		request.getRequestDispatcher("metaDBManage.jsp").forward(request,
				response);
	}

	private void manageDB(HttpServletRequest request,
			HttpServletResponse response) {
		String dbId = RequestUtil.get(request.getParameter("Id"));
		String dbname = dbDao.getDBname(dbId);
		List<Table> tableList = tDao.getTableList(dbId);// 从数据库获取数据
		request.setAttribute("showDBname", dbname);
		request.setAttribute("dbId", dbId);
		try {
			displayTableList(request, response, tableList);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}

	}

	private void manageTable(HttpServletRequest request,
			HttpServletResponse response) {
		String tId = RequestUtil.get(request.getParameter("Id"));
		String tableName = tDao.getTablename(tId);
		List<Field> fieldList = fDao.getFieldListByTid(tId);// 从数据库获取数据
		request.setAttribute("showTablename", tableName);
		request.setAttribute("tableId", tId);
		try {
			displayFieldList(request, response, fieldList);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}

	}

	private void search(HttpServletRequest request, HttpServletResponse response) {
		String name = RequestUtil.get(request.getParameter("search_value"));

		request.setAttribute("searchResult", "metaDBManage.jsp");
		request.setAttribute("searchName", name);
		try {
			if (request.getParameter("search_from").equals("search_db")) {
				List<DataBase> dbList = dbDao.getDBListbyName(name);// 从数据库获取数据
				displayDBList(request, response, dbList);
			}
			if (request.getParameter("search_from").equals("search_table")) {
				List<Table> tableList = tDao.getTableListbyname(name);// 从数据库获取数据
				displayTableList(request, response, tableList);
			}
			if (request.getParameter("search_from").equals("search_field")) {
				List<Field> fieldList = fDao.getFieldListbyTableId(name);// 从数据库获取数据
				displayFieldList(request, response, fieldList);
			}
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}
}
